
#include "StdAfx.h"
#include "CommonFun.h"
#include "../res/resource.h"
#include "WinCrypt.h"
#include "EnDecrypt.h"
#include "shlwapi.h"
#include <WinSock.h>
#include <NB30.h>
#include <iphlpapi.h>
#include "CommonDef.h"

int GYMsgBox(DWORD dwStringId, DWORD dwType)
{
	CString strTitle;
	strTitle.LoadString(IDS_PRODUCT_NAME);

	CString strInfo;
	strInfo.LoadString(dwStringId);

	HWND hWnd = GetActiveWindow();
	return ::MessageBox(hWnd, strInfo, strTitle, dwType);
}

int GYMsgBox(CString strInfo, DWORD dwType)
{
	CString strTitle;
	strTitle.LoadString(IDS_PRODUCT_NAME);

	HWND hWnd = GetActiveWindow();
	return ::MessageBox(hWnd, strInfo, strTitle, dwType);
}

int DataErrorMsgBox(CString strSourceFile, int nLineNumber, CString strSQL, CString strError)
{
	CString strTitle;
	strTitle.LoadString(IDS_PRODUCT_NAME);
	
	CString strErrTpl;
	strErrTpl.LoadString(IDS_GBL_DATA_ERROR);
	
	CString strErrorInfo;
	strErrorInfo.Format(strErrTpl, strSourceFile, nLineNumber, strSQL, strError);

	HWND hWnd = NULL;
	CWnd* pWnd = AfxGetMainWnd();
	if(pWnd)
		hWnd = pWnd->GetSafeHwnd();

	return ::MessageBox(hWnd, strErrorInfo, strTitle, MB_OK|MB_ICONSTOP);
}

CString GetResString(DWORD dwStringId)
{
	CString strInfo;
	strInfo.LoadString(dwStringId);

	return strInfo;
}

BOOL IsFileExist(LPCTSTR lpFile)
{
	return (INVALID_FILE_ATTRIBUTES != ::GetFileAttributes(lpFile) );
}


BOOL SplitPath(const LPTSTR lpszPath, LPTSTR lpszDriver, LPTSTR lpszDir, LPTSTR lpszFileName, LPTSTR lpszExt)
{
	if ( !lpszPath )
		return FALSE;

	if ( lpszDriver != NULL && lpszPath[0]=='\\' && lpszPath[1]=='\\')
	{
		_tcscpy( lpszDriver, _T("\\") );
		_tsplitpath( ( lpszPath+1 ), NULL, lpszDir , lpszFileName, lpszExt );
	}else 
		_tsplitpath( lpszPath, lpszDriver, lpszDir, lpszFileName, lpszExt );	
	
	return TRUE;
}

CString GetExePath()
{
	TCHAR szAppPath[MAX_PATH];
	TCHAR szDrive[MAX_PATH];    
	TCHAR szDir[MAX_PATH];
	TCHAR szFileName[MAX_PATH];
	TCHAR szExt[MAX_PATH];

	::GetModuleFileName(NULL, szAppPath, MAX_PATH);
    SplitPath( szAppPath, szDrive, szDir, szFileName, szExt );
	_tcscpy( szAppPath, szDrive);
    _tcscat( szAppPath, szDir);
	
	int nTemp = _tcsclen(szAppPath);
	szAppPath[nTemp - 1] = '\0';

	return szAppPath;
}

CString GetAppDataPath()
{
	TCHAR szIniPath[MAX_PATH] = {0};
	::SHGetSpecialFolderPath(NULL, szIniPath, CSIDL_APPDATA  , TRUE);
	::PathAppend(szIniPath, _T("GY") );
	if( !IsFileExist(szIniPath) )
	{
		::CreateDirectory( szIniPath , NULL);
	}
	::PathAppend( szIniPath, _T("GYWA1.0") );
	if( !IsFileExist(szIniPath) )
	{
		::CreateDirectory( szIniPath ,NULL);
	}
	
	return szIniPath;
}

CString GetIniFile()
{
	CString strAppDataPath	=	GetAppDataPath();
	strAppDataPath			+=	_T("\\WAAppSet.ini");
	
	return strAppDataPath;
}

CString GetConfigValue(CString strKey)
{
	TCHAR szValue[MAX_PATH] = {0};
	CString strIniPath = GetIniFile();

	::GetPrivateProfileString(_T("USER"), strKey, _T(""), szValue, sizeof(szValue)/sizeof(TCHAR), strIniPath );
	return szValue;
}

BOOL SetConfigValue(CString strKey, CString strValue)
{
	CString strIniFile = GetIniFile();
	return ::WritePrivateProfileString(_T("USER"), strKey, strValue, strIniFile);
}

CString EncryptString(const TCHAR* szIn)
{
	WCHAR szInput[MAX_PATH] = {0};
	WCHAR szOutput[MAX_PATH] = {0};
	
#ifdef _UNICODE
	_tcscpy(szInput, szIn);
#else
	::MultiByteToWideChar(CP_UTF8, NULL, szIn, -1, szInput, MAX_PATH);
#endif

	if(EncryptString(szInput, szOutput))
	{
#ifdef _UNICODE
		return szOutput;
#else
		TCHAR pOut[MAX_PATH] = {0};
		::WideCharToMultiByte(CP_ACP, 0, szOutput, -1, pOut, MAX_PATH, NULL, NULL);
		return pOut;
#endif
	}

	return _T("");
}

CString DecryptString(const TCHAR* szIn)
{
	WCHAR szInput[MAX_PATH] = {0};
	WCHAR szOutput[MAX_PATH] = {0};
	
#ifdef _UNICODE
	_tcscpy(szInput, szIn);
#else
	::MultiByteToWideChar(CP_UTF8, NULL, szIn, -1, szInput, MAX_PATH);
#endif
	
	if(DecryptString(szInput, szOutput))
	{
#ifdef _UNICODE
		return szOutput;
#else
		TCHAR pOut[MAX_PATH] = {0};
		::WideCharToMultiByte(CP_ACP, 0, szOutput, -1, pOut, MAX_PATH, NULL, NULL);
		return pOut;
#endif
	}
	
	return _T("");
}


CString GetIP()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	CString strIP;
	char szName[MAX_PATH] = {0};
	PHOSTENT hostinfo;

	wVersionRequested = MAKEWORD( 2, 0 );
	if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
	{
		if( gethostname ( szName, sizeof(szName)) == 0)
		{
			if((hostinfo = gethostbyname(szName)) != NULL)
			{
				char* ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
#ifdef _UNICODE
				int nLen = strlen(ip);
				TCHAR szIP[MAX_PATH] = {0};
				::MultiByteToWideChar(CP_UTF8, NULL, ip, -1, szIP, nLen);
				strIP = szIP;
#else
				strIP = ip;
#endif
			}
		}
		WSACleanup( );
	}

	return strIP;
}

CString GetMAC()
{
	typedef struct _ASTAT_
	{  
		ADAPTER_STATUS   adapt;   
		NAME_BUFFER   NameBuff[30];       
	}ASTAT, *PASTAT;  
	typedef struct _LANA_ENUM
	{  
		UCHAR length;   
		UCHAR lana[MAX_LANA];
	}LANA_ENUM;       


	TCHAR mac[MAX_PATH] = {0};
	NCB ncb;
	ASTAT Adapter;     
	LANA_ENUM lana_enum;     
	
	UCHAR uRetCode;       
	memset(&ncb, 0, sizeof(ncb)); 
	memset(&lana_enum, 0, sizeof(lana_enum));

	ncb.ncb_command = NCBENUM;
	ncb.ncb_buffer = (unsigned char *)&lana_enum;
	ncb.ncb_length = sizeof(LANA_ENUM);     
	uRetCode = Netbios(&ncb);
	if(uRetCode != NRC_GOODRET)       
		return _T("");
	
	for(int lana=0; lana<lana_enum.length; lana++)       
	{  
		ncb.ncb_command = NCBRESET;
		ncb.ncb_lana_num = lana_enum.lana[lana];
		uRetCode = Netbios(&ncb);
	}   
	if(uRetCode != NRC_GOODRET)  
		return _T("");
	
	memset(&ncb, 0, sizeof(ncb));
	ncb.ncb_command = NCBASTAT;
	ncb.ncb_lana_num = lana_enum.lana[0];
	strcpy((char*)ncb.ncb_callname, "*");
	ncb.ncb_buffer = (unsigned char *)&Adapter;
	ncb.ncb_length = sizeof(Adapter);  
	uRetCode = Netbios(&ncb);   
	if(uRetCode != NRC_GOODRET)     
		return _T("");

	_stprintf(mac, _T("%02X-%02X-%02X-%02X-%02X-%02X"),
		Adapter.adapt.adapter_address[0],       
		Adapter.adapt.adapter_address[1],       
		Adapter.adapt.adapter_address[2],       
		Adapter.adapt.adapter_address[3],       
		Adapter.adapt.adapter_address[4],       
		Adapter.adapt.adapter_address[5]   
		);

	return mac;
}

CString GetMAC2()
{
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
typedef int errno_t;

    PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(sizeof (IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL)
		return _T("");

// Make an initial call to GetAdaptersInfo to get
// the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW)
	{
        FREE(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(ulOutBufLen);
        if (pAdapterInfo == NULL)
			return _T("");

    }

	CString strMAC;
    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR)
	{
        pAdapter = pAdapterInfo;
        while (pAdapter)
		{
			if(pAdapter->Type == MIB_IF_TYPE_ETHERNET && (strstr(pAdapter->Description, "Realtek") || strstr(pAdapter->Description, "PCI") ))
			{
				strMAC.Format(_T("%02X-%02X-%02X-%02X-%02X-%02X"),
								pAdapter->Address[0], 
								pAdapter->Address[1], 
								pAdapter->Address[2], 
								pAdapter->Address[3], 
								pAdapter->Address[4], 
								pAdapter->Address[5]);

				break;
			}
            pAdapter = pAdapter->Next;
        }
    }

    if (pAdapterInfo)
        FREE(pAdapterInfo);

	return strMAC;
}

BOOL IsLeapYear(int nYear)
{
	if((nYear % 400) == 0)
		return TRUE;
	else if((nYear % 100) == 0)
		return FALSE;
	else if((nYear % 4) == 0)
		return TRUE;
	else
		return FALSE;
}


BOOL IsValidDateTime(int nYear, int nMonth, int nDay, int nHour, int nMinute, int nSecond)
{
	BOOL bValid = TRUE;
	
	if(bValid)
		bValid = IsNumInRange(nYear, 1900, 2050);
	
	if(bValid)
		bValid = IsNumInRange(nMonth, 1, 12);
	
	if(bValid)
	{
		switch(nMonth)
		{
		case 1:case 3:case 5:case 7:case 8:case 10:case 12:
			bValid = IsNumInRange(nDay, 1, 31);
			break;

		case 4:case 6:case 9:case 11:
			bValid = IsNumInRange(nDay, 1, 30);
			break;

		case 2:
			if(IsLeapYear(nYear))
				bValid = IsNumInRange(nDay, 1, 29);
			else
				bValid = IsNumInRange(nDay, 1, 28);
			break;
		}
	}
	
	if(bValid)
		bValid = IsNumInRange(nHour, 0, 23);
	
	if(bValid)
		bValid = IsNumInRange(nMinute, 0, 59);
	
	if(bValid)
		bValid = IsNumInRange(nSecond, 0, 59);
	
	return bValid;
}

CString GetDatabasePassword()
{
	CString strIniFile = GetExePath();
	strIniFile += _T("\\");
	strIniFile += GYWA_INI_FILE;
	
	CString strPropName;
	CString strPropValue;
	
	TCHAR szName[MAX_PATH] = {0};
	TCHAR szValue[MAX_PATH] = {0};
	
	int nPropNun = ::GetPrivateProfileInt(_T("Connect"), _T("PropertyNumber"), 0, strIniFile);
	for(int i = 0; i < nPropNun; i++)
	{
		strPropName.Format(_T("PropertyName%02d"), i);
		strPropValue.Format(_T("PropertyValue%02d"), i);
		
		::GetPrivateProfileString(_T("Connect"), strPropName, _T(""), szName, MAX_PATH, strIniFile);
		::GetPrivateProfileString(_T("Connect"), strPropValue, _T(""), szValue, MAX_PATH, strIniFile);
		
		//  Password is encrypted, it need to be decrypted.
		if(_tcsicmp(szName, _T("PWD")) == 0)
		{
			CString strDecryptedPwd = DecryptString(szValue);
			_tcscpy(szValue, strDecryptedPwd);

			return szValue;
		}
	}

	return _T("");
}

CString GetMySQLDumpCmd()
{
	HKEY hKey = NULL;
	HRESULT hr = ::RegCreateKeyEx(HKEY_LOCAL_MACHINE, MYSQL_REG_KEY_PATH, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_QUERY_VALUE, NULL, &hKey, NULL);
	if(ERROR_SUCCESS != hr)
		return _T("");
	
	TCHAR	szMySQLPath[MAX_PATH];
	DWORD	dwSize = sizeof(szMySQLPath);
	hr = ::RegQueryValueEx(hKey, MYSQL_REG_KEY_NAME, NULL, NULL, (LPBYTE)szMySQLPath, &dwSize);
	::RegCloseKey(hKey);
	
	if(ERROR_SUCCESS != hr)
		return _T("");
	
	CString strMySQLPath = szMySQLPath;
	if(strMySQLPath.Right(1) != _T("\\"))
		strMySQLPath += _T("\\");
	
	CString strBinDump = _T("\"");
	strBinDump += strMySQLPath;
	strBinDump += _T("bin\\mysqldump.exe\" gywa -uroot -p");
	strBinDump += GetDatabasePassword();
	strBinDump += _T(" >");
	
	return strBinDump;
}